package com.xy.modular.WeChat.action;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.xy.framework.base.controller.BaseController;
import com.xy.framework.mreturn.MReturnObject;
import com.xy.modular.owner.model.OwnerAuthThird;
import com.xy.modular.owner.service.IOwnerAuthThirdService;
import com.xy.modular.sys.action.ModuleController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(description = "微信授权登录相关接口")
@Controller
@RequestMapping("/wx/login")
public class WeChatLogin extends BaseController {
	// "https://api.weixin.qq.com/sns/jscode2session?
	// appid=wx895b629ee0340df3&secret=0ede38815fa5f39ef1c0cde6faf2e1ed&
	// js_code=023xVCUW1Bagt01tFZSW1f0GUW1xVCUa&grant_type=authorization_code",
	private static final String APPID = "wx895b629ee0340df3";
	private static final String SECRET = "0ede38815fa5f39ef1c0cde6faf2e1ed";

	// 获取凭证校检接口
	static Logger log = LoggerFactory.getLogger(ModuleController.class);

	@Resource
	private IOwnerAuthThirdService ownerAuthThirdService;

	@ApiOperation(value = "登录", notes = "")
	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody MReturnObject login(String code) {
		// 微信的接口
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + SECRET + "&js_code="
				+ code + "&grant_type=authorization_code";
		RestTemplate restTemplate = new RestTemplate();
		// 进行网络请求,访问url接口

		ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
		// 根据返回值进行后续操作
		String sessionData = null;
		if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
			JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
			OwnerAuthThird ownerAuthThird = new OwnerAuthThird(jsonObject.get("openid").toString(),
					jsonObject.get("session_key").toString(), "WXXCX");
			// 获取用户的唯一标识
			// String openid = weChatSession.getOpenid();
			// 获取会话秘钥
			// String session_key = weChatSession.getSession_key();
			// 下面就可以写自己的业务代码了
			// 最后要返回一个自定义的登录态,用来做后续数据传输的验证
			if (ownerAuthThirdService.getById(ownerAuthThird.getOpenid()) != null) {
				ownerAuthThirdService.save(ownerAuthThird);
				return new MReturnObject(MReturnObject.SUCCESS, sessionData);
			} else {
				return new MReturnObject(MReturnObject.ERROR, null);
			}
		}
		return new MReturnObject(MReturnObject.ERROR, null);
	}
}
